from subprocess import Popen
from typing import Dict
import shutil
import sys

BROWSERS = {
	"win32": {
		"Chrome": [
			"C:/Program Files/Google/Chrome/Application/chrome.exe",
			"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
		],
        "Firefox": [
            "C:/Program Files/Mozilla Firefox/firefox.exe",
			"C:/Program Files (x86)/Mozilla Firefox/firefox.exe"
		],
        "Edge": [
            "C:/Program Files/Microsoft/Edge/Application/msedge.exe",
			"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
		]
	},
	"darwin": {
		"Chrome": [
            "/Applications/Google Chrome.app"
		],
        "Firefox": [
			"/Applications/Firefox.app"
		],
        "Safari": [
			"/Applications/Safari.app"
		]
	},
	"linux": {
		"Chrome": [
            "chromium",
			"chrome"
		],
        "Firefox": [
            "firefox"
		],
        "Edge": [
            "microsoft-edge"
		]
	}
}


def get_available_browsers() -> Dict[str, str]:
	browsers = {"Default": ""}
	for browser, paths in BROWSERS[sys.platform].items():
		for path in paths:
			if browser not in browsers and shutil.which(path):
				browsers[browser] = path
	return browsers


def open_browser(path: str, address: str):
	if path == "":
		open_default_browser(address)
		return
	args = ["--no-default-browser-check", "--no-first-run", "--foreground", "--new-window", address]
	if sys.platform == "win32":
		Popen([path] + args)
	elif sys.platform == "darwin":
		Popen(["open", "-a", path, "--args"] + args)
	elif sys.platform == "linux":
		Popen([path] + args)


def open_default_browser(address: str):
	if sys.platform == "win32":
		Popen(["rundll32", "url.dll,FileProtocolHandler", address])
	elif sys.platform == "darwin":
		Popen(["open", "-u", address])
	elif sys.platform == "linux":
		Popen(["xdg-open", address])
